//
//  YYENoteDetailsViewController.m
//  YuYingEDU
//
//  Created by 胡波 on 2018/1/25.
//  Copyright © 2018年 胡波. All rights reserved.
//

#import "YYENoteDetailsViewController.h"
#import "YYENoteCommentsViewController.h"
#import "YYENotesTableViewCell.h"
#import "YYENoteCommentTableViewCell.h"
#import "YYENoteCommentModel.h"
#import "YSLCustomButton.h"

@interface YYENoteDetailsViewController () <UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong) YYEBaseTableView *tableView;
@property (nonatomic,strong) NSMutableArray *datas;
@property (nonatomic,strong) UIButton *commentBtn;
@property (nonatomic,strong) UIButton *praiseBtn;
@property (nonatomic,strong) YSLCustomButton *likeBtn;

@end

@implementation YYENoteDetailsViewController

static NSString * noteCell = @"noteCell";
static NSString * commentCell = @"commentCell";

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"正文";
    
    [self configUI];
    
    [self configBottomView];
    
    [self loadData];
    
}

- (void)configBottomView {
    
    UIView *contentView = [[UIView alloc]init];
    contentView.backgroundColor = GeneralBackColor;
    [self.view addSubview:contentView];
    
    self.commentBtn = [[UIButton alloc]init];
    [self.commentBtn setImage:[UIImage imageNamed:@"comment"] forState:UIControlStateNormal];
    [self.commentBtn addTarget:self action:@selector(commentClicked) forControlEvents:UIControlEventTouchUpInside];
    [contentView addSubview:self.commentBtn];
    
    self.praiseBtn = [[UIButton alloc]init];
    if ([self.noteModel.is_liked isEqualToString:@"1"]) {
        self.praiseBtn.selected = YES;
    }
    [self.praiseBtn setImage:[UIImage imageNamed:@"unpraise"] forState:UIControlStateNormal];
    [self.praiseBtn setImage:[UIImage imageNamed:@"praise"] forState:UIControlStateSelected];
    [self.praiseBtn addTarget:self action:@selector(likeClicked:) forControlEvents:UIControlEventTouchUpInside];
    [contentView addSubview:self.praiseBtn];
    
    [contentView makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.height.equalTo(45);
    }];
    
    [self.commentBtn makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.top.equalTo(contentView);
        make.width.equalTo(SCREEN_WIDTH / 2);
    }];
    
    [self.praiseBtn makeConstraints:^(MASConstraintMaker *make) {
        make.right.top.bottom.equalTo(contentView);
        make.width.equalTo(SCREEN_WIDTH / 2);
    }];
    
}

- (void)loadData {
    
    NSDictionary *dic = @{
                          @"uid":[LoginModel shareLogin].uid,
                          @"username":[LoginModel shareLogin].username,
                          @"token":[LoginModel shareLogin].token,
                          @"notes_id":self.noteModel.id
                          };
    [SVProgressHUD show];
    [AFNHelper post:NoteComment parameters:dic success:^(id responseObject) {
        
        NSLog(@"%@",responseObject);
        if (responseObject[@"status"]) {
            self.datas = [YYENoteCommentModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
            [self.tableView reloadData];
        }
        [SVProgressHUD showWithStatus:responseObject[@"message"]];
        [SVProgressHUD dismiss];
        
    } faliure:^(id error) {
        
        NSLog(@"请求失败");
        [SVProgressHUD showWithStatus:ShowError];
        [SVProgressHUD dismissWithDelay:0.5];
        
    }];
    
}

- (void)configUI {
    
    [self.view addSubview:self.tableView];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self.tableView registerClass:[YYENotesTableViewCell class] forCellReuseIdentifier:noteCell];
    [self.tableView registerClass:[YYENoteCommentTableViewCell class] forCellReuseIdentifier:commentCell];
    
    [self.tableView makeConstraints:^(MASConstraintMaker *make) {
//        make.edges.equalTo(UIEdgeInsetsZero);
        make.edges.equalTo(UIEdgeInsetsMake(0, 0, 45, 0));
    }];
    
}

- (YYEBaseTableView *)tableView {
    
    if (!_tableView) {
        _tableView = [[YYEBaseTableView alloc]initwithDelegate:self];
    }
    return _tableView;
    
}

- (NSMutableArray *)datas {
    
    if (!_datas) {
        _datas = [NSMutableArray array];
    }
    return _datas;
    
}

- (void)commentClicked {
    
    YYENoteCommentsViewController *commentVC = [[YYENoteCommentsViewController alloc]init];
    [self.navigationController pushViewController:commentVC animated:YES];
    
}

- (void)likeClicked:(UIButton *)button {
    
    button.selected = !button.selected;
    if ([button isSelected]) {
        
        NSLog(@"点赞");
        NSInteger praise = self.noteModel.like_count.integerValue + 1;
        self.noteModel.is_liked = @"1";
        self.noteModel.like_count = @(praise).stringValue;
        [self.likeBtn setTitle:@(praise).stringValue forState:UIControlStateSelected];
        [self.likeBtn setSelected:YES];
    }else {
        
        NSLog(@"取消点赞");
        NSInteger praise = self.noteModel.like_count.integerValue - 1;
        self.noteModel.is_liked = @"0";
        self.noteModel.like_count = @(praise).stringValue;
        if (self.noteModel.like_count.integerValue > 0) {
            [self.likeBtn setTitle:@(praise).stringValue forState:UIControlStateNormal];
        }else {
            [self.likeBtn setTitle:@"" forState:UIControlStateNormal];
        }
        [self.likeBtn setSelected:NO];
    }
    
}

#pragma mark -- UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 2;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (section == 0) {
        return 1;
    }else {
        return self.datas.count;
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        
        YYENotesTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:noteCell];
        
        cell.lineView.hidden = YES;
        cell.bottomView.hidden = YES;
        cell.commentBtn.hidden = YES;
        cell.praiseBtn.hidden = YES;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.model = self.noteModel;
        cell.deleteBtn.hidden = YES;
        
        return cell;
        
    }else {
        
        YYENoteCommentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:commentCell];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.commentModel = self.datas[indexPath.row];
        
        return cell;
        
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        
        CGSize sizeForLabel = [self.noteModel.note boundingRectWithSize:CGSizeMake(SCREEN_WIDTH - 34, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,NSFontAttributeName:[UIFont systemFontOfSize:14]} context:nil].size;
        if (self.noteModel.image.length > 0) {
            return 276.5 + sizeForLabel.height;
        }else {
            return 68.5 + sizeForLabel.height;
        }
        
    }else {
        
        YYENoteCommentModel *model = self.datas[indexPath.row];
        CGSize sizeForLabel = [model.comment boundingRectWithSize:CGSizeMake(SCREEN_WIDTH - 34, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,NSFontAttributeName:[UIFont systemFontOfSize:13]} context:nil].size;
        
        return sizeForLabel.height + 46;;
        
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    if (section == 0) {
        return 0.01;
    }else {
        return 36;
    }
    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    if (section == 0) {
        
        return nil;
        
    }else {
        
        UIView *contentView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 36)];
        contentView.backgroundColor = [UIColor whiteColor];
        
        UILabel *commentLabel = [[UILabel alloc]init];
        commentLabel.textColor = [UIColor blackColor];
        commentLabel.font = [UIFont systemFontOfSize:15];
        [contentView addSubview:commentLabel];
        
        self.likeBtn = [[YSLCustomButton alloc]init];
        [self.likeBtn setTitleColor:GeneralGrayColor forState:UIControlStateNormal];
        [self.likeBtn setTitleColor:GeneralDarkRed forState:UIControlStateSelected];
        self.likeBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        if ([self.noteModel.is_liked isEqualToString:@"1"]) {
            self.likeBtn.selected = YES;
        }else if ([self.noteModel.is_liked isEqualToString:@"0"]) {
            self.likeBtn.selected = NO;
        }
        [self.likeBtn setImage:[UIImage imageNamed:@"unpraise"] forState:UIControlStateNormal];
        [self.likeBtn setImage:[UIImage imageNamed:@"praise"] forState:UIControlStateSelected];
        self.likeBtn.ysl_buttonType = YSLCustomButtonImageLeft;
        self.likeBtn.ysl_spacing = 3;
        [contentView addSubview:self.likeBtn];
        
        UIView *lineView = [[UIView alloc]init];
        lineView.backgroundColor = LightLineColor;
        [contentView addSubview:lineView];
        
        commentLabel.text = [NSString stringWithFormat:@"评论 %ld",self.datas.count];
        if (self.noteModel.like_count.integerValue > 0) {
            [self.likeBtn setTitle:self.noteModel.like_count forState:UIControlStateNormal];
        }else {
            [self.likeBtn setTitle:@"" forState:UIControlStateNormal];
        }
        
        [commentLabel makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(contentView.left).offset(12);
            make.centerY.equalTo(contentView.centerY);
        }];
        
        [self.likeBtn makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(contentView.right).offset(-12);
            make.centerY.equalTo(contentView.centerY);
            make.size.equalTo(CGSizeMake(30, 20));
        }];
        
        [lineView makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(contentView);
            make.height.equalTo(0.5);
        }];
        
        return contentView;
        
        
    }

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
